<template>
  <div class="app-container" v-loading="loading">
    <el-tabs class="allTab" v-model="activeName" type="border-card" @tab-click="handleClick">
      <el-tab-pane label="期权试算" name="first">
        <el-form :inline="true" class="demo-form-inline">
          <el-form-item>
            <el-dropdown class="right-menu-item hover-effect" trigger="click">
              <div class="avatar-wrapper">
                <el-button type="primary" plain icon="Plus" v-hasPermi="['calc:otcOtion:basestructure']" size="small">
                  基础结构
                </el-button>
              </div>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item
                      v-for="item in OptionList"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value"
                      @click="createNode(item.value)"
                  >{{item.label}}</el-dropdown-item>
<!--                  <el-dropdown-item @click="createNode('vanilla')">香草期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('digital')">二元期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('doubleDigital')">双层二元</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('multiDigital')">三层阶梯</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('touch')">触碰期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('SingleSharkFin')">单鲨期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('doubleShark')">双鲨期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('doubleBarrier')">双障碍期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('rangeaccrual')">区间累计期权</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('basicsnowball')">保本雪球</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('standardsnowball')">非保本返息雪球</el-dropdown-item>-->
<!--                  <el-dropdown-item @click="createNode('flooredsnowball')">限亏型雪球</el-dropdown-item>-->
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </el-form-item>
          <el-form-item label="计算日期">
            <el-date-picker
                v-model="calcPricingParam.valueDate"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="定价环境" prop="cfgId">
            <baseCombox url="/pricing/comboBox/queryPriceCfg4Local.action"
                        ref="cfgIdRef"
                        clearable
                        valueField="cfgId"
                        labelField="name"
                        size="small"
                        @defaultSelect="(value) => {calcPricingParam.cfgId = value}"
                        :defaultSelectIndex="'0'"
                        :queryParam="{productType:'OtcOption'}"
                        style="width: 240px" placeholder="定价配置" v-model="calcPricingParam.cfgId"></baseCombox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" v-hasPermi="['calc:otcOtion:calAll']" @click="calcOptionAll">计算全部</el-button>
            <el-button type="danger" v-hasPermi="['calc:otcOtion:removeAll']" icon="Delete" @click="delAll">清除全部
            </el-button>
            <!--          <el-icon><document /></el-icon>-->
            <el-button type="primary" v-hasPermi="['calc:otcOtion:save2Trade']" icon="Document" @click="save2Trade">
              转簿记
            </el-button>
            <el-button type="primary" v-hasPermi="['calc:otcOtion:importCalc']" v-whatEnviron="['hyhl']" icon="Headset" @click="testSpeech">
              试定价导入
            </el-button>
          </el-form-item>
        </el-form>
        <el-dialog v-model="dialog2DocumentVisible" :close-on-click-modal="false"   title="转簿记" width="20%" draggable>
          <el-form ref="dialog2DocumentForm" :model="instrument2TradeFrom.data" :rules="dialog2documentformrules">
            <!--          <el-form-item label="组合"  label-width="90px">
                        <baseCombox  url="/pricing/group/queryVGroupCombox.action"
                                     clearable
                                     multiple="true"
                                     valueField="dict_val"
                                     labelField="dict_disp"
                                     size="small"
                                     placeholder="组合"    ></baseCombox>

                      </el-form-item>-->
            <el-form-item label="本方账户" prop="accId" label-width="90px">
              <baseCombox url="/trade/account/querySelfAccountCombox.action"
                          clearable
                          valueField="accId"
                          labelField="accName"
                          size="small"
                          v-model="instrument2TradeFrom.data.accId"
                          :style="{width: '100%'}" placeholder="本方账户"></baseCombox>
            </el-form-item>
            <el-form-item label="交易对手" label-width="90px" prop="partyId">
              <baseCombox v-model="instrument2TradeFrom.data.partyId"
                          clearable
                          labelField="partyName"
                          url="/trade/counterparty/queryCounterparty4Combox.action"
                          size="small"
                          valueField="partyId"
                          :style="{width: '100%'}" placeholder="对手"></baseCombox>
            </el-form-item>
            <el-form-item label="产品编号" label-width="90px" prop="extTradeId">
              <el-input v-model="instrument2TradeFrom.data.extTradeId" maxlength="100" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="合约编号" label-width="90px" prop="iCode">
              <el-input v-model="instrument2TradeFrom.data.iCode" maxlength="100" autocomplete="off"></el-input>
            </el-form-item>
            <el-form-item label="交易日期" label-width="90px" prop="tradeDate">
              <el-date-picker v-model="instrument2TradeFrom.data.tradeDate" placeholder="选择日期" type="date"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="期初保证金" label-width="90px" prop="margin" v-show="false">
              <el-row style="width: 100%;">
                <el-col :span="6">
                  <el-select v-model="instrument2TradeFrom.data.marginDirection" placeholder="请选择" style="width:100%">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
                </el-col>
                <el-col :span="18">
                  <InputAmount v-model:value="instrument2TradeFrom.data.margin" maxlength="20" append="元" autocomplete="off"
                               precision="2"/>
                </el-col>
              </el-row>
            </el-form-item>

            <el-form-item label="前端费支付方向" label-width="90px" prop="frontFee">
                  <el-select v-model="instrument2TradeFrom.data.frontFeeDirection" placeholder="请选择" style="width:100%">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
            </el-form-item>
            <el-form-item label="前端费" label-width="90px" prop="frontFee">
              <el-row  style="width: 100%;" >
                <el-col :span="10"><el-checkbox v-model="instrument2TradeFrom.data.frontFeeYear" @change="onfrontFeeRateChange()"  name="status" false-label="0" true-label="1">年化
                </el-checkbox></el-col>

                <el-col :span="14"> <Numberinput v-model="instrument2TradeFrom.data.frontFeeRate" :max="1000000000" :min="0" append="%" width="100%"
                                                precision="2" @blur="onfrontFeeRateChange()"/></el-col>
              </el-row>
              <el-row style="width: 100%;" >
                <InputAmount v-model:value="instrument2TradeFrom.data.frontFee" maxlength="20" append="元" width="100%"
                                               autocomplete="off" @blur="onfrontFeeChange()"
                                               precision="2"/>
              </el-row>
            </el-form-item>
            <el-form-item label="前端费支付日" label-width="90px" prop="frontFeePaydate">
              <el-date-picker v-model="instrument2TradeFrom.data.frontFeePaydate" placeholder="选择日期" type="date"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="期权费支付方向" label-width="90px" prop="fee">
                  <el-select v-model="instrument2TradeFrom.data.feeDirection" placeholder="请选择" style="width:100%">
                    <el-option label="支付" value="-1"/>
                    <el-option label="收取" value="1"/>
                  </el-select>
            </el-form-item>
            <el-form-item label="期权费" label-width="90px" prop="fee">
              <el-row  style="width: 100%;">
                    <el-col :span="10"><el-checkbox v-model="instrument2TradeFrom.data.feeYear" @change="onFeeRateChange()" name="status" false-label="0" true-label="1">年化
                    </el-checkbox></el-col>
                    <el-col :span="14"> <Numberinput v-model="instrument2TradeFrom.data.feeRate" :max="1000000000" :min="0" append="%" width="100%"
                                                    precision="2" @blur="onFeeRateChange()"/></el-col>
              </el-row>
              <el-row style="width: 100%;" >
                    <InputAmount v-model:value="instrument2TradeFrom.data.fee" maxlength="20" append="元" width="100%"
                                                   autocomplete="off" @blur="onFeeChange()"
                                                   precision="2"/>
              </el-row>
            </el-form-item>
            <el-form-item label="期权费支付日" label-width="90px" prop="setDate">
              <el-date-picker v-model="instrument2TradeFrom.data.setDate" placeholder="选择日期" type="date"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="提前终止日期" label-width="90px" prop="terminateDate" v-show="false">
              <el-date-picker v-model="instrument2TradeFrom.data.terminateDate" placeholder="选择日期" type="date"
                              value-format="YYYY-MM-DD">
              </el-date-picker>
            </el-form-item>
            <el-form-item label="提前终止费用" label-width="90px" prop="terminateFee" v-show="false">
              <InputAmount v-model:value="instrument2TradeFrom.data.terminateFee" append="元"
                           autocomplete="off"
                           precision="2"/>
            </el-form-item>
            <el-form-item label="备注" label-width="90px" prop="remark">
              <el-input v-model="instrument2TradeFrom.data.remark" maxlength="300" autocomplete="off" type="textarea"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialog2DocumentVisible = false">取消</el-button>
        <el-button type="primary" @click="save2Document()">确认</el-button>
      </span>
          </template>
        </el-dialog>
        <el-dialog v-model="dialog2implCalcVisible" :close-on-click-modal="false"   title="试定价导入" width="30%" draggable>
          <div>
            <el-row :gutter="20" >
              <el-col :span="24"><el-input v-model="implCalcText" :rows="20" type="textarea" /></el-col>
<!--              <el-col style="align-self: center;" :span="4"><el-button type="primary" size="large" @mousedown.native="start"
                                           @mouseup.native="stop"
                                           icon="Mute" title="长按录音，松开停止" >录音</el-button></el-col>-->
            </el-row>
          </div>
          <template #footer>
            <span class="dialog-footer">
              <el-button @click="dialog2implCalcVisible = false">取消</el-button>
              <el-button type="primary" @click="save2implCalc()">确认</el-button>
            </span>
          </template>
        </el-dialog>
        <el-dialog v-loading="loading" v-model="dialog2CalcLogVisible" :close-on-click-modal="false" title="保存定价草稿"
                   width="30%" draggable>
          <el-form ref="dialog2CalcLogRef" :model="instrument2CalcLogData.data" :rules=" instrument2calclogrules">
            <el-form-item label="名称" prop="draftName" label-width="90px">
              <el-input v-model="instrument2CalcLogData.data.draftName"></el-input>
            </el-form-item>
            <el-form-item label="交易对手" label-width="90px" prop="partyId">
              <baseCombox v-model="instrument2CalcLogData.data.partyId"
                          clearable
                          labelField="partyName"
                          url="/trade/counterparty/queryCounterparty4Combox.action"
                          size="small"
                          valueField="partyId"
                          :style="{width: '100%'}" placeholder="对手"></baseCombox>
            </el-form-item>

            <el-form-item label="备注" label-width="90px" prop="remark">
              <el-input v-model="instrument2CalcLogData.data.remark" autocomplete="off" type="textarea"></el-input>
            </el-form-item>
          </el-form>
          <template #footer>
      <span class="dialog-footer">
        <el-button @click="dialog2CalcLogVisible = false">取消</el-button>
        <el-button type="primary" @click="save2Log()">确定</el-button>
      </span>
          </template>
        </el-dialog>

        <el-scrollbar width="auto">
          <!--   计算结果     -->
          <div class="option-total-table-header">
            <el-table :data="getTotalResult()" border :header-cell-style="getRowClass">
              <el-table-column align="center" prop="npv" label="npv" width="180" :formatter="(row)=>Number(row.npv).toLocaleString()"/>
              <el-table-column align="center" prop="npvPercentage" label="npv%" width="180"/>
              <el-table-column align="center" prop="yearnpvPercentage" label="yearnpv%" width="180" />
              <el-table-column align="center" prop="delta" label="delta" :formatter="(row)=>Number(row.delta).toLocaleString()"/>
              <el-table-column align="center" prop="deltacash" label="deltacash" :formatter="(row)=>Number(row.deltacash).toLocaleString()"/>
              <el-table-column align="center" prop="gamma" label="gamma" :formatter="(row)=>Number(row.gamma).toLocaleString()"/>
              <el-table-column align="center" prop="gammacash" label="gammacash" :formatter="(row)=>Number(row.gammacash).toLocaleString()"/>
              <el-table-column align="center" prop="vega" label="vega" :formatter="(row)=>Number(row.vega).toLocaleString()"/>
              <el-table-column align="center" prop="theta" label="theta" :formatter="(row)=>Number(row.theta).toLocaleString()"/>
              <el-table-column align="center" prop="rho" label="rho" :formatter="(row)=>Number(row.rho).toLocaleString()"/>
            </el-table>
          </div>
          <!--   期权条款     -->
          <div id='instruments' style="display: inline-flex">
            <div class="instrumentList" v-for="(v,i) in instruments" v-bind:key="i"
                 style="display: inline-flex;margin: 3px 0px 0px 0px;">
              <component :is="getInstrument(instruments[i].optionType)" v-if="instruments[i].flag" v-loading="instruments[i].loading"
                         :del="del" :calc="calcOption" :isReCalc="instruments[i].isReCalc"
                         :copy="copy" :marketNPV="calcMarketNPV"
                         :ref="'instrument'+instruments[i].index"
                         :setformData="setformData"
                         :formData="instruments[i].formData"
                         :index="instruments[i].index"
                         :cfgId="instruments[i].cfgId"
                         :getDefaultCfg="getDefaultCfg"
                         :save2Trade="OpenDialog2Document"
                         :save2CalcLog="OpenDialog2CalcLog"
                         :calcPricingParam="instruments[i].calcPricingParam"
                         :valueDate="calcPricingParam.valueDate"
                         :result="instruments[i].result"
                         :calcMarketNpvResult="instruments[i].calcMarketNpvResult"
                         :calcSuccess="instruments[i].calcSuccess"
                         :errorMsg="instruments[i].errorMsg"
                         :cacheFormData="cacheFormData"
              />
            </div>
          </div>
        </el-scrollbar>

      </el-tab-pane>
      <el-tab-pane label="情景分析" name="second">
        <scene/>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>


<script lang="ts" setup name="OtcOption">
import {defineAsyncComponent, getCurrentInstance, onMounted, provide, ref, reactive, watch, computed} from 'vue'
import {formartFormP2, formartFormP4, formartTableP2, unFormartNumber, numberPrecision} from "@/utils/numberUtil";
import {
  calcMarket,
  saveCalcLogs,
  getInstrumentList,
  getDefaultPricingParam,
  getCalendar,
  marketNPV
} from '@/api/calc/otcOption/calc'
import {insertTrade} from '@/api/trade/otcoptiontrade'
import baseCombox from "@/xquant/base/baseCombox";
import InputAmount from '@/xquant/base/InputAmount'
import Numberinput from '@/xquant/base/number'
import {useRouter} from "vue-router";
import {useStore} from "vuex";
import {isNotVoid,isVoid,zhDigitToArabic,calcAnnualizedByTerminationPaymentDate} from "../../../utils/util";
import {getOptionList,getInstrument} from "@/views/calc/otcOtion/instrument/common/common";
import {debounce} from 'lodash'
import GolbalStore from '@/store'
const OptionList = ref([])
const router = useRouter();
const store = useStore();
const {proxy} = getCurrentInstance();
const getRowClass = ({row, column, rowIndex, columnIndex}) => {
  if (rowIndex == 0) {
    return {background: '#E79942', color: '#606266'}
  } else {
    return {background: '#E79942', color: '#606266'}
  }
}

const loading = ref(false)
const scene = defineAsyncComponent(() => import ('./scene/index.vue'))


const activeName = ref('first')
const dialog2DocumentVisible = ref(false)
const dialog2implCalcVisible = ref(false)
const dialog2CalcLogVisible = ref(false)
const instrument2TradeFrom = reactive({
  data: {
    iCode: '',
    extTradeId:'',
    accId: '',
    partyId: '',
    margin: '',
    amount: '',
    tradeDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    remark: '',
    fee: '',
    feeRate: '',
    feeYear: '1',
    feeDirection: '',
    setDate: '',
    marginDirection: '',
    frontFeeDirection:'',
    frontFee:'',
    frontFeeYear:'1',
    frontFeeRate:'',
    frontFeePaydate:'',
    terminateDate:'',
    terminateFee:'',
  }
})

const dialog2documentformrules = reactive({
  iCode: [{required: true, message: ' ', trigger: 'change'}],
  extTradeId:[{required: false, message: ' ', trigger: 'change'}],
  accId: [{required: true, message: ' ', trigger: 'change'}],
  // partyId: [{required: true, message: ' ', trigger: 'change'}],
  margin: [{required: false, message: ' ', trigger: 'change'}],
  amount: [{required: true, message: ' ', trigger: 'change'}],
  tradeDate: [{required: true, message: ' ', trigger: 'change'}],
  marginDirection: [{required: true, message: ' ', trigger: 'change'}],
  setDate: [{required: false, message: ' ', trigger: 'change'}],
  feeDirection: [{required: true, message: ' ', trigger: 'change'}],
  remark: [{required: false, message: ' ', trigger: 'change'}],
  frontFeeDirection: [{required: true, message: ' ', trigger: 'change'}],
  frontFee:[{required: false, message: ' ', trigger: 'change'}],
  frontFeePaydate:[{required: false, message: ' ', trigger: 'change'}],
  terminateDate:[{required: false, message: ' ', trigger: 'change'}],
  terminateFee:[{required: false, message: ' ', trigger: 'change'}],
})

const instrument2calclogrules = reactive({
  draftName: [{required: true, message: ' ', trigger: 'change'}, {
    validator: (rule, value, callback) => {
      return String(value).length < 26
    }, message: '长度不超25个字符', trigger: 'change'
  }],
  // partyId: [{required: true, message: ' ', trigger: 'change'}],
  margin: [{required: false, message: ' ', trigger: 'change'}],
  amount: [{required: true, message: ' ', trigger: 'change'}],
  tradeDate: [{required: true, message: ' ', trigger: 'change'}],
  remark: [{required: false, message: ' ', trigger: 'change'}],
})
const calcPricingParam = reactive({
  valueDate: proxy.$moment(new Date()).format("YYYY-MM-DD"),
  cfgId: '',
})
let implCalcText = ref("") ;
let instruments = reactive([])
const getCardWidth = () => {
  if (instruments.length == 0 || instruments.length < 5) {
    return 400 * 4;
  } else {
    return 400 * instruments.length;
  }
}
let index = 0
watch(() => calcPricingParam.cfgId, (nv, ov) => {
  if (nv != ov) {
    for (let instrument of instruments) {
      instrument.cfgId = nv;
    }
  }
})


function calcMarketNPV(data, index, flag) {
  marketNPV(data, index, flag).then(response => {
    if (response.errorCode != 0) {
      proxy.$modal.msgError("计算出错！\n" + response.errorMsg);
    } else {
      /*      if (flag != "All") {
            }*/
      index = instruments.map(item => item.index).indexOf(index)
      let result = response.result;
      instruments[index]['calcMarketNpvResult'] = {
        volRate: result.volRates.double[0]
      };
      instruments[index].result["status"] = 1;
      proxy.$modal.msgSuccess("计算成功！");
    }
  });
}

/*期权市场计算接口，所有子组件都会用到*/
function calcOption(data, index, flag) {
  instruments[index]['calcSuccess'] = ""
  let volSurface = data.calcPricingForm.volSurface;
  if (volSurface&&Number(volSurface.rate)<=0) {
    proxy.$modal.msgWarning("波动率不能为0");
    return
  }else if(isNaN(volSurface.rate)&&isVoid(volSurface.code)) {
    proxy.$modal.msgWarning("波动率不能为空");
    return
  }
  instruments[index].loading = true
  calcMarket(data, index, flag).then(response => {
    instruments[index].loading = false
    if (response.errorCode != 0) {
      instruments[index]['calcSuccess'] = "false"
      instruments[index]['errorMsg'] = response.errorMsg
      proxy.$modal.msgError(response.errorMsg);
    } else {
      if (flag != "All") {
        proxy.$modal.msgSuccess("计算成功！");
      }
      let result = response.result;
      var param = {}
      param.condition = data.instrument.termsheet.underlyerIds[0]
      let annualized = calcAnnualizedByTerminationPaymentDate(data.calcInstrumentForm)
      let other = {
        "npvPercentage": formartFormP4(100 * result.contract.npv / data.instrument.termsheet.notional),
        "yearnpvPercentage": formartFormP4(100 * result.contract.npv / data.instrument.termsheet.notional /annualized),
        "gammacash": formartFormP2(response.result.contract.gamma * response.result.contract.spotPrice * response.result.contract.spotPrice / 100),
        "deltacash": formartFormP2(response.result.contract.delta * response.result.contract.spotPrice)
      }
      resultList.push(Object.assign(response.result.contract, other));
      index = instruments.map(item => item.index).indexOf(index)
      response.result.contract.spotPrice = Number(response.result.contract.spotPrice).toFixed(2)
      instruments[index].result = Object.assign(response.result.contract, other);
      instruments[index].result["status"] = 1;
      instruments[index]['calcSuccess'] = "true"
    }
  });
}

function calcOptionAll() {
  let calc = [];
  for (let instrument of instruments) {
    let refIndex = "instrument" + instrument.index;
    if (proxy.$refs[refIndex].length>0||instrument.flag) {
      proxy.$refs[refIndex][0].calc("All")
    }
  }
}

const getDefaultCfg = (optionJson, index) => {
  if (optionJson.instrument.termsheet.underlyerIds.length > 0 && optionJson.instrument.termsheet.underlyerIds[0] != '') {
    getDefaultPricingParam(optionJson).then(response => {
      if (response.errorCode != 0) {

      } else {
        let {underlyingPricingParams, discount, calcPPCode} = response.result.calcPricingParam;
        let {spotQuoteType, dividend, volSurface} = underlyingPricingParams[0];
        let ppcfg = {
          calcPPCode: calcPPCode,
          spotQuoteType: spotQuoteType,
          dividend: dividend,
          discount: discount,
          volSurface: volSurface
        }
        index = instruments.map(item => item.index).indexOf(index)
        instruments[index].calcPricingParam = ppcfg;
        return response.result.calcPricingParam
      }
    })
  }
}

function del(current) {
  current = instruments.map(item => item.index).indexOf(current)
  instruments[current].flag = false;
  // instruments.splice(current, 1)
  RefreshPage()
}

function delAll() {
  // instruments.length = 0;
  instruments.forEach(item => { item.flag = false })
  RefreshPage()
}

function copy(current) {
  setformData(current);
  current = instruments.map(item => item.index).indexOf(current)
  let cloneDeep = proxy.lsh.cloneDeep(instruments[current]);
  cloneDeep.formData.data.result = {}
  var ele = {
    index: 0,
    isReCalc:true,
    flag: true,
    optionType: cloneDeep.optionType,
    result: {},
    cfgId: calcPricingParam.cfgId,
    formData: cloneDeep.formData,
    calcPricingParam: cloneDeep.calcPricingParam || {}
  };
  ele.index = index;
  //复制form 数据
  instruments.push(ele);
  index++;
  RefreshPage()
}

const createNode= debounce(function (optionType) {
  if (getInstrument(optionType)) {
    var ele = {
      index: 0,
      flag: true,
      isReCalc: false,
      optionType: optionType,
      calcPricingParam: {},
      result: {},
      cfgId: calcPricingParam.cfgId
    };
    ele.index = index;
    instruments.push(ele);
    index++;
    RefreshPage()
    return ele.index;
  }
},1000)

function RefreshPage() {
  if (instruments.length > 4) {
    window.dispatchEvent(new Event('resize')); // 触发window的resize事件
  }
}

function setformData(current) {
  //设置定价参数
  setPriceParam(current)
  current = instruments.map(item => item.index).indexOf(current)
  let refIndex = "instrument" + instruments[current].index;
  instruments[current].formData = proxy.$refs[refIndex][0].getFormData();
}

function setPriceParam(current) {
  //设置定价参数
  current = instruments.map(item => item.index).indexOf(current)
  let refIndex = "instrument" + instruments[current].index;
  instruments[current].calcPricingParam = proxy.$refs[refIndex][0].getCalcPriceParam()
  return
}

const instrument2TradeData = reactive({
  data: {}
})
const instrument2CalcLogData = reactive({
  data: {}
})

function save2Trade() {
  if (instruments.length > 0) {
    let a = instruments.filter(item => item.flag)
    if (a.length>1){
      proxy.$modal.msgWarning("转簿记仅支持单腿结构！");
      return
    }
    let refIndex = "instrument" + a[0].index;
    proxy.$refs[refIndex][0].getInstrumentJson().then((res) => {
      if (Boolean(res)) {
        OpenDialog2Document(res)
      }
    })
  } else {
    proxy.$modal.msgWarning("至少录入一个期权结构");
  }

}

function OpenDialog2Document(otcOption) {
  dialog2DocumentVisible.value = true;
  instrument2TradeFrom.data={
    iCode: '',
    extTradeId:'',
    accId: '',
    partyId: '',
    margin: '',
    amount: '',
    tradeDate: proxy.$moment(new Date()).format('YYYY-MM-DD'),
    remark: '',
    fee: '',
    feeYear:'1',
    feeDirection: '',
    setDate: '',
    marginDirection: '',
    frontFeeDirection:'',
    frontFee:'',
    frontFeeYear:'1',
    frontFeePaydate:'',
    terminateDate:'',
    terminateFee:'',
  };
  instrument2TradeData.data = otcOption
}

function OpenDialog2CalcLog(otcOption) {
  dialog2CalcLogVisible.value = true;

  instrument2CalcLogData.data = otcOption
  instrument2CalcLogData.data.valueDate = calcPricingParam.valueDate
}

function save2Document() {
  let instrument = instrument2TradeData.data.otcOption.instrument;
  let calcInstrumentForm = instrument2TradeData.data.calcInstrumentForm;
  let calcPricingForm = instrument2TradeData.data.calcPricingForm;
  let calcResultForm = instrument2TradeData.data.calcResultForm;

  /*处理期权费*/
  instrument.termsheet["legs"].push({
    "legId": "leg02",
    "payDirection": Number(instrument2TradeFrom.data.feeDirection)
  //  instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection)
  })
  instrument.termsheet["customLegs"].push({
    "legId": "leg02",
    "productType": "Premium",
    "paymentDate": instrument2TradeFrom.data.setDate,
    "paymentConv": "NONE",
    "paymentAmount": instrument2TradeFrom.data.fee,
    "paymentCurrency": "CNY"
  })

  proxy.$refs['dialog2DocumentForm'].validate(valid => {
    if (valid) {
      //如果金额不为0或空 则首付方向必输
      if(isNotVoid(instrument2TradeFrom.data.margin)&&instrument2TradeFrom.data.margin>0&&!isNotVoid(instrument2TradeFrom.data.marginDirection)){
        proxy.$modal.alertWarning('请设置保证金收付方向!')
        return
      }
      if(isNotVoid(instrument2TradeFrom.data.fee)&&instrument2TradeFrom.data.fee>0&&!isNotVoid(instrument2TradeFrom.data.feeDirection)){
        proxy.$modal.alertWarning('请设置期权费收付方向!')
        return
      }

      if(isNotVoid(instrument2TradeFrom.data.fee)&&instrument2TradeFrom.data.fee>0&&!isNotVoid(instrument2TradeFrom.data.setDate)){
        proxy.$modal.alertWarning('请设置期权费收付日期!')
        return
      }


      if(isNotVoid(instrument2TradeFrom.data.frontFee)&&instrument2TradeFrom.data.frontFee>0&&!isNotVoid(instrument2TradeFrom.data.frontFeeDirection)){
        proxy.$modal.alertWarning('请设置前端费收付方向!')
        return
      }

      if(isNotVoid(instrument2TradeFrom.data.frontFee)&&instrument2TradeFrom.data.frontFee>0&&!isNotVoid(instrument2TradeFrom.data.frontFeePaydate)){
        proxy.$modal.alertWarning('请设置前端费费收付日期!')
        return
      }

      var trade = {
        // 交易要素
        extTradeId:instrument2TradeFrom.data.extTradeId,
        optionType:calcInstrumentForm.optionType,
        frontFee:instrument2TradeFrom.data.frontFee* Number(instrument2TradeFrom.data.frontFeeDirection),
        frontFeePaydate:instrument2TradeFrom.data.frontFeePaydate,
        frontFeeRate:instrument2TradeFrom.data.frontFeeRate ,
        frontFeeYear: instrument2TradeFrom.data.frontFeeYear,
        frontOptionFee: instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection),
        frontOptionFeePaydate: instrument2TradeFrom.data.setDate,
        frontOptionFeeRate: instrument2TradeFrom.data.feeRate ,
        frontOptionFeeYear: instrument2TradeFrom.data.feeYear,
        terminateDate:instrument2TradeFrom.data.terminateDate,
        terminateFee: instrument2TradeFrom.data.terminateFee,
        tradeType: Boolean(instrument.termsheet.legs) ?
             (instrument.termsheet.legs[0].payDirection == "-1" ? "OtcOptionSell" : "OtcOptionBuy")
            :(instrument.termsheet.payDirection == "-1" ? "OtcOptionSell" : "OtcOptionBuy") ,
        volume: instrument.termsheet.notional,
        spotPrice: Boolean(instrument.termsheet.customLegs) ?  instrument.termsheet.customLegs[0].underlyers[0].spotPrice: instrument.termsheet.issuePrice,
        aType: 'CTM',
        mType: 'NONE',
        currency: instrument.termsheet.notionalCurrency,
        /* trade.extInfo = Ext.encode(me.extInfoFieldSet.getValue());*/
        tradeDate: instrument2TradeFrom.data.tradeDate,
        accId: instrument2TradeFrom.data.accId,
        partyId: instrument2TradeFrom.data.partyId,
        iCode: instrument2TradeFrom.data.iCode,
        price: Boolean(instrument.termsheet.customLegs) ?  instrument.termsheet.customLegs[0].underlyers[0].spotPrice: instrument.termsheet.issuePrice,
        // trade.setDate : me.dateFieldFeePayDate.getRawValue(),
        margin: instrument2TradeFrom.data.margin * Number(instrument2TradeFrom.data.marginDirection),
        fee: instrument2TradeFrom.data.fee * Number(instrument2TradeFrom.data.feeDirection),
        setDate: instrument2TradeFrom.data.setDate,
        // trade.amount : me.cbxPayDirection.getValue() * me.amtFieldFee.getAmount(),
        // trade.currency : me.amtFieldFee.getCurrency(),
        remark: instrument2TradeFrom.data.remark,
        // trade.relatedProducts : me.relatedProducts.getValue(),
        // trade.txtSupAgrId : me.txtSupAgrId.getValue(),
        ocFlag: "O",
        calcInstrumentForm: calcInstrumentForm,
        calcPricingForm: calcPricingForm,
        calcResultForm: calcResultForm,
        // 金融工具要素
        instrumentInfo: {
          pCalc: JSON.stringify(instrument),
          instrumentId: instrument.termsheet.underlyerIds[0],
          currency: instrument.termsheet.notionalCurrency,
          pNotional: 1,
          country: 'CN',
          qType: 'Dp',
          pName: instrument.productType,
          pType: instrument.productType,
          pClass: instrument.productType,
          issueDate: instrument.termsheet.effectiveDate,
          maturityDate: instrument.termsheet.terminationDate,
          settlementType: "C",
          // calendar: calendar,
          bizdayConvertion: instrument.termsheet.effectiveDateConv
        }
      }
      loading.value = true;
      insertTrade(trade).then((res) => {
        if (res.success) {
          proxy.$modal.msgSuccess("保存成功！");
          proxy.$refs['dialog2DocumentForm'].resetFields()
          dialog2DocumentVisible.value = false;
        } else {
          proxy.$modal.msgError("出错！\n" + JSON.stringify(res.msg));
        }

        loading.value = false;
      })
    }
  })

}

function save2Log() {

  saveCalcLogs(instrument2CalcLogData.data).then((res) => {
    if (res.success) {
      proxy.$modal.msgSuccess("保存成功！");
      dialog2CalcLogVisible.value = false;q
      proxy.$refs['dialog2CalcLogRef'].resetFields()
    } else {
      proxy.$modal.msgError("出错！\n" + JSON.stringify(res.msg));
    }
  })
}


var resultList = reactive([])

function getTotalResult() {
  let tableData = {
    npv: "",
    npvPercentage: "",
    delta: "",
    deltacash: "",
    gamma: "",
    gammacash: "",
    vega: "",
    theta: "",
    rho: ""
  };

  if (instruments.length == 1) {
    if (instruments[0] == undefined) {
    } else {
      tableData.npv = instruments[0].result.npv == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.npv)));
      tableData.npvPercentage = instruments[0].result["npvPercentage"] == undefined ? '' : formartFormP4((unFormartNumber(instruments[0].result["npvPercentage"])));
      
      tableData["yearnpvPercentage"] = instruments[0].result["yearnpvPercentage"] == undefined ? '' : formartFormP4((unFormartNumber(instruments[0].result["yearnpvPercentage"])));
      tableData.delta = instruments[0].result.delta == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.delta)));
      tableData.deltacash = instruments[0].result.deltacash == undefined ? '' : formartFormP2(unFormartNumber(instruments[0].result.deltacash));
      tableData.gamma = instruments[0].result.gamma == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.gamma)));
      tableData.gammacash = instruments[0].result.gammacash == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.gammacash)));
      tableData.vega = instruments[0].result.vega == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.vega)));
      tableData.theta = instruments[0].result.theta == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.theta)));
      tableData.rho = instruments[0].result.rho == undefined ? '' : formartFormP2((unFormartNumber(instruments[0].result.rho)));
    }
  } else {
    for (let i = 0; i < instruments.length; i++) {
      if (instruments[i].result.npv&&instruments[i].flag) {
        tableData.npv = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.npv)), (unFormartNumber(instruments[i].result.npv))))
        tableData["npvPercentage"] = formartFormP4(proxy.lsh.add((unFormartNumber(tableData["npvPercentage"])), (unFormartNumber(instruments[i].result["npvPercentage"]))))
        tableData["yearnpvPercentage"] = formartFormP4(proxy.lsh.add((unFormartNumber(tableData["yearnpvPercentage"])), (unFormartNumber(instruments[i].result["yearnpvPercentage"]))))
        tableData.delta = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.delta)), (unFormartNumber(instruments[i].result.delta))))
        tableData.deltacash = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.deltacash)), (unFormartNumber(instruments[i].result.deltacash))))
        tableData.gamma = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.gamma)), (unFormartNumber(instruments[i].result.gamma))))
        tableData.gammacash = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.gammacash)), (unFormartNumber(instruments[i].result.gammacash))))
        tableData.vega = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.vega)), (unFormartNumber(instruments[i].result.vega))))
        tableData.theta = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.theta)), (unFormartNumber(instruments[i].result.theta))))
        tableData.rho = formartFormP2(proxy.lsh.add((unFormartNumber(tableData.rho)), (unFormartNumber(instruments[i].result.rho))))
      }
    }
  }
  return [tableData]
}

watch(() => instruments, (nv, ov) => {
  cacheFormData()
},{deep:true})

function cacheFormData() {
  if (proxy.isNotVoid(router.currentRoute.value.query)) {
    let refIndex = "instrument" + instruments[0].index;
    if (isVoid(proxy.$refs[refIndex])){ return}
    let formData = proxy.$refs[refIndex][0].getFormData()
    let {dataId} = router.currentRoute.value.query;
    var { pFormPricing, pFormInstrument, productType, pFormResult} = router.currentRoute.value.query;
    var map = GolbalStore.getters.cache;
    let cacheObj = {}
    cacheObj[dataId+''] = {
      'pForm': JSON.stringify(formData.data),
      'pFormInstrument': JSON.stringify(formData.data),
      'pFormPricing': pFormPricing,
      'productType': productType,
      'pFormResult': pFormResult,
    }
    store.commit("SET_Map", cacheObj);
  }
}
function initCompent() {
  if (proxy.isNotVoid(router.currentRoute.value.query)) {

    var map = GolbalStore.getters.cache;
      let {dataId} = router.currentRoute.value.query;
      if (isNotVoid(map)&&isNotVoid(map[dataId+''])){
        var {pForm, pFormPricing, pFormInstrument, productType, pFormResult} = map[dataId+''];
      }else {
        var {pForm, pFormPricing, pFormInstrument, productType, pFormResult} = router.currentRoute.value.query;
      }
    var ele = {
      index: index,
      flag: true,
      isReCalc: JSON.parse(String(pFormPricing)) != null,
      optionType: String(productType).toLowerCase(),
      result: JSON.parse(String(pFormResult)) || {},
      formData: JSON.parse(String(pFormInstrument)) || {},
      calcPricingParam: JSON.parse(String(pFormPricing)) || {}
    }
    ele.formData.initFlag = true
    /*设置当时的定价日期*/
    if (JSON.parse(pForm).calcPricingParam && pForm) {
      calcPricingParam.valueDate = JSON.parse(pForm).calcPricingParam.valueDate
    }
    instruments.push(ele)
    index++;

  }
}

onMounted(() => {
  initCompent();
  getOptionList().then(res=>{
    OptionList.value = res;
  });
})
const getIndex = (index) => {
  let arr = instruments.filter(item=>{return item.flag})
  return arr.map(item=> item.index).indexOf(index) + 1
}
const getIndexRef = (index)=>{
  return proxy.$refs['instrument'+index]
}
provide('getIndex',getIndex)
provide('getIndexRef',getIndexRef)

function save2implCalc() {
  loading.value = true
  dialog2implCalcVisible.value = false
  let str = implCalcText.value;
  let optionType = '';
   // str = "九坤投资gex9买入500指数香草期权, 6m, 行权价120%, 期权费1.10%，名义本金300万元，14：25-14：35 wind TAWP价格，20210729起息";
  if (str.includes('香草')) {
    str = str.replaceAll('，',',')
    let strArr = str.split(',')
    let form = {};
    optionType = 'vanilla'
    let instrmentiName = '';
    if (strArr[0].includes('买入')) {
      instrmentiName = strArr[0].split('买入')[1].replace("香草期权","")
    }else {
      instrmentiName = strArr[0].split('卖出')[1].replace("香草期权","")
    }
    getInstrumentList({
      iName:instrmentiName=='500指数'?'中证'+instrmentiName:instrmentiName
    }).then(res=>{
      form['instrumentId'] = res[0].code
      form['payDirection'] = strArr[0].includes('买入')?'1':'-1';
      form['term'] = strArr[1].match(/\d+/g) * 30
      form['strikePercentage'] = strArr[2].match(/\d+/g) * 1
      form['feePercentage'] = strArr[3].match(/\d+\.\d+?/g) * 1
      form['notional'] = strArr[4].match(/\d+/g) * 10000
      form['effectiveDate'] = proxy.$moment(strArr[6].match(/\d+/g), "YYYYMMDD").format('YYYY-MM-DD')
      let indexstr = createNode(optionType)
      instruments[indexstr]['formData'] = form
      loading.value = false

    })

  }
  if (str.includes('雪球')) {
    if (str.includes('限赔结构雪球')) {
      /*
      * 中证500限赔结构雪球，12M，无锁定期，敲入线60%，敲出线80%，预付金0%，限赔10%，敲出票息15.2%，
      * */

      let strArr = str.split('，')
      let form = {};
      optionType = 'flooredsnowball'
      let instrmentiName = ''
      instrmentiName = strArr[0].split('限赔')[0]
      getInstrumentList({
        iName:instrmentiName=='500指数'?'中证'+instrmentiName:instrmentiName
      }).then(res=>{
        form['instrumentId'] = res.length>0?res[0].code:''
        // form['payDirection'] = strArr[1].includes('买入')?'1':'-1';
        form['term'] = strArr[1].match(/[^\d]/g) * (strArr[1].includes('M')?30:(strArr[1].includes('Y')?365:1))
        form['feePercentage'] = strArr[3].match(/\d+\.?\d+/g) * 1
        // form['notional']
        // form['effectiveDate'] = proxy.$moment(strArr[8].match( /\d{4}(-\d{1,2}){2}/g)[0], "YYYY-MM-DD").subtract(1,'months').format('YYYY-MM-DD')
        form['knockInLevelPercentage'] = strArr[3].match(/\d+\.?\d+/g) * 1
        form['konckLevelPercentage'] = strArr[4].match(/\d+\.?\d+/g) * 1
        form['knockOutYield'] = strArr[7].match(/\d+\.\d+?/g) * 1
        form['knockInParticipationRate'] =  100
        form['knockInStrikePercentage'] =  100
        let indexstr = createNode(optionType)
        instruments[indexstr]['formData'] = form
        loading.value = false

      })

    }

    if (str.includes('常规'))  {
      /*
      * 您好，
      * 我司（xx有限公司）向贵司买入如下常规雪球结构，
      * 名义本金规模二亿元人民币，
      * 期初贵司（产品）需向我司支付初始保证金合计 875,000.00元 挂钩中证500指数，
      * 一年期，
      * 60-80 常规雪球，
      * 锁6M后月敲出观察，
      * 票息年化 2.60% 收盘价定盘 非授信模式，
      * 交易确认书以此附件为模板
      * 敲出观察日如下（遇节假日向后顺延）
      * 2021-7-29 2021-8-29 2021-9-29 2021-10-31 2021-11-29 2021-12-29 2022-1-30 2022-2-28 2022-3-29 2022-5-2
      * */
      let strArr = str.split('，')
      let form = {};
      optionType = 'standardsnowball'
      let instrmentiName = ''
      instrmentiName = strArr[3].split('挂钩')[1]
      getInstrumentList({
        iName:instrmentiName=='500指数'?'中证'+instrmentiName:instrmentiName
      }).then(res=>{
        form['instrumentId'] = res.length>0?res[0].code:''
        form['payDirection'] = strArr[1].includes('买入')?'1':'-1';
        form['term'] = strArr[4].includes("一年")?'365':''
        form['feePercentage'] = strArr[3].match(/\d+\.\d+?/g) * 1
        form['notional'] =zhDigitToArabic(strArr[2].split('规模')[1].split('人民币')[0])
        form['effectiveDate'] = proxy.$moment(strArr[8].match( /\d{4}(-\d{1,2}){2}/g)[0], "YYYY-MM-DD").subtract(1,'months').format('YYYY-MM-DD')
        form['knockInLevelPercentage'] = strArr[5].split(' ')[0].split('-')[0]
        form['konckLevelPercentage'] = strArr[5].split(' ')[0].split('-')[1]
        form['knockOutYield'] = strArr[7].match(/\d+\.\d+?/g) * 1
        form['knockInParticipationRate'] =  100
        form['knockInStrikePercentage'] =  100
        let indexstr = createNode(optionType)
        instruments[indexstr]['formData'] = form
        loading.value = false

      })

    }
  }

  implCalcText.value = ''
}
const onfrontFeeRateChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.data.calcInstrumentForm)
  let notional = instrument2TradeData.data.calcInstrumentForm.notional
  if ('1' == instrument2TradeFrom.data.frontFeeYear) {
    instrument2TradeFrom.data.frontFee = Number(notional * instrument2TradeFrom.data.frontFeeRate / 100 *annualized)
  }else {
    instrument2TradeFrom.data.frontFee = Number(notional * instrument2TradeFrom.data.frontFeeRate /100)
  }
}
const onfrontFeeChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.data.calcInstrumentForm)
  let notional = instrument2TradeData.data.calcInstrumentForm.notional
  if ('1' == instrument2TradeFrom.data.frontFeeYear) {
    instrument2TradeFrom.data.frontFeeRate = Number(instrument2TradeFrom.data.frontFee/notional /annualized * 100)
  }else {
    instrument2TradeFrom.data.frontFeeRate = Number(instrument2TradeFrom.data.frontFee/notional * 100)
  }
}
const onFeeChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.data.calcInstrumentForm)
  let notional = instrument2TradeData.data.calcInstrumentForm.notional
  if ('1' == instrument2TradeFrom.data.feeYear) {
    instrument2TradeFrom.data.feeRate = Number(instrument2TradeFrom.data.fee/notional /annualized * 100)
  }else {
    instrument2TradeFrom.data.feeRate = Number(instrument2TradeFrom.data.fee/notional * 100)
  }
}
const onFeeRateChange = () => {
  let annualized = calcAnnualizedByTerminationPaymentDate(instrument2TradeData.data.calcInstrumentForm)
  let notional = instrument2TradeData.data.calcInstrumentForm.notional
  if ('1' == instrument2TradeFrom.data.feeYear) {
    instrument2TradeFrom.data.fee = Number(notional * instrument2TradeFrom.data.feeRate / 100 *annualized)
  }else {
    instrument2TradeFrom.data.fee = Number(notional * instrument2TradeFrom.data.feeRate /100)
  }
}
/*录音函数*/
let newRecognition = new webkitSpeechRecognition();
newRecognition.lang = 'cmn-Hans-CN';
newRecognition.continuous = false;
function testSpeech() {
  dialog2implCalcVisible.value=true

  // 开启
  // newRecognition.start();

// 停止
//   newRecognition.stop();
  newRecognition.onresult = function(event) {
    implCalcText.value += event.results[0][0].transcript;

  }
}
function start() {
  newRecognition.start();
}
function stop() {
  newRecognition.stop();
}
</script>
<style>
.block {
  margin: 1rem;
}

.demonstration {
  margin: 1rem;
}

.instrumentList {
  flex: content-box;
  float: left;
  display: inline-flex;
  font-size: 14px;
  justify-content: space-between;
}

.delete:hover {
  background-color: #F2F6FC;
}

/deep/ .allTab {
  overflow-y: scroll; /*y轴溢出显示滚动条*/
}

</style>
